package com.example.status;

import com.example.bean.WaterSenSorFunction;
import com.example.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.state.MapState;
import org.apache.flink.api.common.state.MapStateDescriptor;
import org.apache.flink.api.common.state.ReducingState;
import org.apache.flink.api.common.state.ReducingStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * ClassName: KeyedListStatusDemo
 * Package: com.example.status
 * Description:
 * User: fzykd
 *
 * @Author: LQH
 * Date: 2023-07-21
 * Time: 16:12
 */


// Map状态
public class KeyedReducingStateDemo {
    public static void main(String[] args) throws Exception {

        //1.创建执行环境

        StreamExecutionEnvironment env =
                StreamExecutionEnvironment.getExecutionEnvironment();

        env.setParallelism(1);

        SingleOutputStreamOperator<WaterSensor> dataTime = env.socketTextStream("hadoop103", 7777)
                //读进来之后 map算子转换
                .map(new WaterSenSorFunction())
                //生成水位线
                //assign 分配  Timestamps时间戳 和 水位线
                //这个方法的参数是 WatermarkStrategy(接口) 水位线生成策略
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                //方法前面 加一个泛型？？
                                //指定 水位线是单调升序  还是乱序
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3)) //表示乱序 最大诚信3秒
                                //从数据中提取事件时间 withTimestampAssigner (带有时间戳的生成器)
                                .withTimestampAssigner(new SerializableTimestampAssigner<WaterSensor>() {
                                    @Override
                                    public long extractTimestamp(WaterSensor element, long recordTimestamp) {
                                        //获取数据的时间戳 单位是毫秒
                                        return element.getTs() * 1000L;
                                    }
                                })
                );

        //统计每种传感器每种水位值出现的次数。
        dataTime.keyBy(value -> value.getId())
                .process(
                        //计算每种传感器的水位和
                        new KeyedProcessFunction<String, WaterSensor, String>() {
                            //创建Reducing状态
                            ReducingState<Integer> vcSum;
                            @Override
                            public void open(Configuration parameters) throws Exception {
                                //初始值状态
                                vcSum = getRuntimeContext().getReducingState(
                                        //reducing 描述符
                                        new ReducingStateDescriptor<Integer>(
                                                "sum",  //名字
                                                new ReduceFunction<Integer>() {
                                                    //第二个参数 定义规约函数 和 前面的一样 自定义逻辑 两两怎么规约
                                                    @Override
                                                    public Integer reduce(Integer value1, Integer value2) throws Exception {
                                                        return value1 + value2;
                                                    }
                                                },
                                                Types.INT//规约操作的数据类型
                                        )
                                );
                            }
                            @Override
                            public void processElement(WaterSensor value, Context ctx, Collector<String> out) throws Exception {
                                //来一条数据 添加进 reduce 自己就累加了
                                vcSum.add(value.getVc());

                                out.collect("传感器id为" + value.getId() + "水位值总和= " + vcSum.get());
                            }
                        }
                ).print();





        env.execute();
    }
}
